# @Time : 2021/4/7 13:50
# @Author : Fioman 
# @Phone : 13149920693
"""
浏览器控制模块,主要用来打开浏览器,以及一些配置
"""
import webbrowser as wbr
from eel import chrome
import subprocess


def build_url_from_dict(page):
    """
    当page是字典的时候构建
    :param page:
    :return:
    """
    scheme = page.get('scheme', 'http')
    host = page.get('host', 'localhost')
    port = page.get('port', 8000)
    path = page.get('path', '')
    return '%s://%s:%d/%s' % (scheme, host, port, path)


def build_url_from_string(page, options):
    """
    当page是字符串的时候构建
    :param page:
    :param options:
    :return:
    """
    baseUrl = 'http://%s:%d/' % (options['host'], options['port'])
    return baseUrl + page


def build_urls(startUrls, options):
    """
    构建urls
    :param startUrls:
    :param options:
    :return:
    """
    urlList = []
    for page in startUrls:
        if isinstance(page, dict):
            url = build_url_from_dict(page)
        else:
            url = build_url_from_string(page, options)
        urlList.append(url)
    return urlList


def open_chrome(startUrls, options):
    """
    打开浏览器
    :param startUrls:首页路由
    :param options: 打开的一些参数配置
    :return:
    """
    startUrls = build_urls(startUrls, options)
    if options['mode'] in ['chrome', 'chrome-app']:
        chrome.run(options, startUrls)
    elif options['mode'] in [None, False]:
        pass  # Don't open a browser
    elif options['mode'] == 'custom':
        subprocess.Popen(options['args'],
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         stdin=subprocess.PIPE)
    else:
        # Use system default browser
        for url in startUrls:
            wbr.open(url)
